package fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.ProgressCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Policy;
import java.util.ArrayList;
import java.util.List;

import co.yeye.test.Constance;
import co.yeye.test.MainActivity;
import co.yeye.test.R;
import developers.AboutDeveloper;
import developers.BeDeveloper;
import register.Login;

/**
 * Created by yeye on 15/2/23.
 */
public class AboutFragment extends Fragment implements NetworkAlert.setAlertDialog {

    Button tittle;
    TextView content,about;

    public static AboutFragment newInstance(){
        AboutFragment fragment  = new AboutFragment();
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.about_layout, container, false);
        tittle = (Button) rootView.findViewById(R.id.refresh_text);
        tittle.setVisibility(View.GONE);

        // 配置关于文字
        content = (TextView) rootView.findViewById(R.id.about_content);
        about = (TextView) rootView.findViewById(R.id.about_version);
        // 配置按钮
        Button btn_toBeDeveloper,btn_aboutDeveloper,btn_update;
        btn_toBeDeveloper = (Button) rootView.findViewById(R.id.btn_about_to_be_developer);
        btn_aboutDeveloper = (Button) rootView.findViewById(R.id.btn_about_developer);
        btn_update = (Button) rootView.findViewById(R.id.btn_about_update);

        ArrayList<Button> btnList = new ArrayList<Button>();
        btnList.add(btn_toBeDeveloper);
        btnList.add(btn_aboutDeveloper);
        btnList.add(btn_update);
        setBtnListener(btnList);

        // 获取网络状态
        int networkState = MainActivity.getInstance().getNetState();
        if(networkState==Constance.NETWORK_INVALID)
            setTittle(getResources().getString(R.string.network_invalid),
                    getResources().getColor(R.color.red), 0);
        //else
        //setText();

        return rootView;
    }

    public void setText(){
        // 获取VersionCode
        final PackageInfo pi;
        try {
            pi = getActivity().getBaseContext().getPackageManager().getPackageInfo(
                    getActivity().getBaseContext().getPackageName(), 0);
        }catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        // 配置关于文字
        AVQuery<AVObject> query = new AVQuery<AVObject>("Version");
        query.whereEqualTo("code", pi.versionCode);
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> avObjects, AVException e) {
                if(e==null&&avObjects.size()!=0){
                    content.setText(avObjects.get(0).getString("info"));
                }
                else{
                    e.printStackTrace();
                }
            }
        });
        about.setText("version "+pi.versionName);
    }

    private void setBtnListener(ArrayList<Button> btnList){
        btnList.get(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!Constance.isUserLogin()){
                    Toast.makeText(getActivity().getBaseContext(),"请登录",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), Login.class);
                    startActivity(intent);
                }
                else{
                    Intent intent = new Intent(getActivity(), BeDeveloper.class);
                    startActivity(intent);
                }
            }
        });

        btnList.get(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), AboutDeveloper.class);
                startActivity(intent);
            }
        });

        btnList.get(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTittle("正在获取版本信息",getResources().getColor(R.color.red),0);
                // 获取VersionCode
                final PackageInfo pi;
                try {
                    pi = getActivity().getBaseContext().getPackageManager().getPackageInfo(
                            getActivity().getBaseContext().getPackageName(), 0);
                }catch (PackageManager.NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return;
                }
                AVQuery<AVObject> query = new AVQuery<AVObject>("Version");
                query.orderByDescending("code");
                query.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(final List<AVObject> avObjects, AVException e) {
                        tittle.setVisibility(View.GONE);
                        if(e==null){
                            if(avObjects.size()<=0){
                                Toast.makeText(getActivity().getBaseContext(),
                                        "无可用版本信息",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if(Integer.valueOf(avObjects.get(0).getString("stringCode"))==
                                    pi.versionCode){
                                Toast.makeText(getActivity().getBaseContext(),
                                        "当前为最新版本",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                    .setTitle("检测到新版本！")
                                    .setMessage("版本号:"+avObjects.get(0).getString("stringCode")+
                                    "\n版本信息:"+avObjects.get(0).getString("new_feature"))
                                    .setNegativeButton("取消",new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {

                                        }
                                    })
                                    .setPositiveButton("升级",new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            // 新建进度条对话框
                                            final downloadDialog progressDialog =
                                                    new downloadDialog(getActivity());
                                            progressDialog.setMessage("正在下载");
                                            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                            progressDialog.setMax(100);
                                            progressDialog.show();
                                            // 开始获取然后下载
                                            AVFile file = avObjects.get(0).getAVFile("file");
                                            file.getDataInBackground(new GetDataCallback() {
                                                @Override
                                                public void done(byte[] bytes, AVException e) {
                                                    try {
                                                        OutputStream os = new FileOutputStream(
                                                                getActivity().getExternalCacheDir()+
                                                                        "release.apk");
                                                        os.write(bytes);
                                                        os.close();
                                                    }catch (IOException fe){
                                                        fe.printStackTrace();
                                                    }

                                                }
                                            },new ProgressCallback() {
                                                @Override
                                                public void done(Integer integer) {
                                                    progressDialog.setProgress(integer);
                                                }
                                            });
                                        }
                                    })
                                    .show();
//                            Toast.makeText(getActivity().getBaseContext(),
//                                    "检测到新版本，版本号为:"+avObjects.get(0).getString("stringCode"),
//                                    Toast.LENGTH_SHORT).show();
                        }
                        else {
                            Toast.makeText(getActivity().getBaseContext(), "获取新版本错误",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    class downloadDialog extends ProgressDialog{
        public downloadDialog(Context context) {
            super(context);
        }

        @Override
        public void setProgress(int value) {
            super.setProgress(value);
            if(value>=100)
                onStop();
        }

        @Override
        protected void onStop() {
            super.onStop();
            dismiss();
            this.setMessage("正在跳转至安装");
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            String filePath = getActivity().getExternalCacheDir()+
                    "release.apk";
            File file = new File(filePath);
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        }
    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time ){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                }
            }, time);
        }
    }

    /**
     * 网络变更通知
     */
    public void networkChanged(int state){
        // 先判断是否获取了tittle
        boolean isNull = tittle==null ? true : false;
        if(state==Constance.NETWORK_INVALID){
            if(!isNull)
                setTittle(getResources().getString(R.string.network_invalid),
                        getResources().getColor(R.color.red),0);
        }
        else {
            if(!isNull)
                tittle.setVisibility(View.GONE);
            NetworkAlert networkAlert = new NetworkAlert(this, state);
            networkAlert.start();
        }
    }

    @Override
    public void execute() {
        setText();
    }
}
